import { DrawerFormInlineType } from "./type";
import { fetchAllMenu, getTreeDataOptionsId } from "./utils";
export const tableLoading = ref(false);
export const addLoading = ref(false);
export const formInline = reactive<any>({});
export const visible = ref<boolean>(false);
export let parentArray: any = ref([]);
let checkedArray: any = [];
const deepTreeDataOptions = (array: any, idsData: any) => {
  array.forEach((item: any) => {
    if (
      (idsData[item.value] && [2, 3].includes(item.is_menu)) ||
      (idsData[item.value] &&
        [0, 1].includes(item.is_menu) &&
        !item?.children?.length)
    )
      checkedArray.push(item.value);
    else if (idsData[item.value]) parentArray.value.push(item.value);

    if (item?.children?.length) deepTreeDataOptions(item.children, idsData);
  });
};
export const resetFormInline = (formState) => {
  const defaultFormInline = reactive<DrawerFormInlineType>({
    id: undefined,
    name: undefined,
    slug: undefined,
    permission_ids: [],
    desc: undefined,
  });
  Object.keys(defaultFormInline).forEach((key) => {
    formState[key] = defaultFormInline[key];
  });
};
resetFormInline(formInline);
export const set_formInline = async (
  type: string,
  formInline: any,
  data?: any
) => {
  resetFormInline(formInline);
  if ((type === "edit" && data) || type === "view") tableLoading.value = true;
  if (type === "add") addLoading.value = true;
  await fetchAllMenu(powerOptions);
  const tmpPowerOptions = ref(deepClone(powerOptions.value));
  if ((type === "edit" && data) || type === "view") tableLoading.value = false;
  if (type === "add") addLoading.value = false;
  visible.value = true;
  const permissionIdsData = {};
  const permissionIds = data?.permission_ids?.split(",") || [];
  permissionIds.forEach((id: any) => {
    permissionIdsData[id] = true;
  });
  if ((type === "edit" && data) || type === "view") {
    Object.keys(formInline).forEach(
      (key: any) => (formInline[key] = data[key] ?? formInline[key])
    );
    checkedArray = [];
    parentArray.value = [];
    deepTreeDataOptions(powerOptions.value, permissionIdsData);
    formInline.permission_ids = [...new Set(checkedArray)];
  }
  if (!isEmptyType(powerOptions.value)) {
    if (operateType.value != "view") {
      tmpArray.value = [];
      getTreeDataOptionsId(tmpPowerOptions.value);
      checkedAll.value = permissionIds.length === tmpArray.value.length;
    }
  }
};
export const operateType = ref<any>("");
export const powerOptions = ref<any>([]);
export const tmpArray = ref<any>([]);
export let checkedAll = ref<any>(false);
export const checkboxRef = ref<any>(null);
